package com.jspxcms.plug.web.back;

import com.jspxcms.common.orm.LimitRequest;
import com.jspxcms.common.orm.Limitable;
import com.jspxcms.common.orm.RowSide;
import com.jspxcms.common.web.Servlets;
import com.jspxcms.core.domain.UserDetail;
import com.jspxcms.core.service.UserDetailService;
import com.jspxcms.core.service.UserService;
import com.jspxcms.core.support.Constants;
import com.jspxcms.core.support.Context;
import com.jspxcms.plug.domain.*;
import com.jspxcms.plug.service.PlugDiseaseService;
import com.jspxcms.plug.service.UserExchangeService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.web.PageableDefaults;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.*;

import static com.jspxcms.core.support.Constants.*;

@Controller
@RequestMapping("/plug/gift")
public class GiftController {
    private static final Logger logger = LoggerFactory
            .getLogger(GiftController.class);

    @RequiresPermissions("plug:gift:list")
    @RequestMapping("list.do")
    public String list(
            @PageableDefaults(sort = "id", sortDir = Direction.DESC)
            Pageable pageable,
            HttpServletRequest request,
            HttpServletResponse response,
            org.springframework.ui.Model modelMap) {

        Map<String, String[]> params = Servlets.getParameterValuesMap(request, Constants.SEARCH_PREFIX);
        Page<UserExchange> pagedList = userExchangeService.findByUserId(null, null, pageable.getPageNumber(), pageable.getPageSize());
        modelMap.addAttribute("pagedList", pagedList);
        return "plug/gift/gift_list";
    }

    @RequiresPermissions("plug:gift:edit")
    @RequestMapping("edit.do")
    public String edit(
            Integer id,
            @PageableDefaults(sort = "id", sortDir = Direction.DESC) Pageable pageable,
            HttpServletRequest request,
            org.springframework.ui.Model modelMap) {
        UserExchange bean = userExchangeService.findById(id);
        Integer userId = bean.getUserId();
        UserDetail userDetail = userDetailService.get(userId);
        modelMap.addAttribute("userDetail", userDetail);
        modelMap.addAttribute("bean", bean);
        modelMap.addAttribute(OPRT, EDIT);
        return "plug/gift/gift_form";
    }


    @RequiresPermissions("plug:gift:update")
    @RequestMapping("update.do")
    public String update(
            @ModelAttribute("bean")
            UserExchange bean,
            Integer state,
            Integer position,
            String redirect,
            RedirectAttributes ra) {

        if (canPay(bean, bean.getGoodsScore())) {
            bean.setSuccess(state);
            bean.setAuditDate(new Date());
            userExchangeService.update(bean);
            logger.info("update UserExchange, name={}.", bean.getGoodsTitle());
        }
        ra.addFlashAttribute(MESSAGE, SAVE_SUCCESS);
        if (Constants.REDIRECT_LIST.equals(redirect)) {
            return "redirect:list.do";
        } else {
            ra.addAttribute("id", bean.getId());
            ra.addAttribute("position", position);
            return "redirect:edit.do";
        }
    }


    /**
     * 判断积分是否足够支付
     *
     * @param bean
     * @param score
     * @return
     */
    private boolean canPay(UserExchange bean, Integer score) {
        if (bean == null || score == null)
            return false;
        UserExchange byId = userExchangeService.findById(bean.getId());
        if (byId != null) {
            UserDetail userDetail = userDetailService.get(byId.getUserId());
            if (userDetail != null) {
                if (userDetail.getScore() != null && userDetail.getScore() > score) {
                    userDetailService.updateScore(byId.getUserId(), 0 - score);
                    return true;
                }
            }
        }
        return false;
    }


    @ModelAttribute("bean")
    public UserExchange preloadBean(@RequestParam(required = false) Integer oid) {
        return oid != null ? userExchangeService.findById(oid) : null;
    }


    @Autowired
    private UserExchangeService userExchangeService;

    @Autowired
    private UserService userService;

    @Autowired
    private UserDetailService userDetailService;
}
